package com.ccys.common.third.sms;


import com.ccys.common.util.StringUtil;
import com.nexmo.client.NexmoClient;
import com.nexmo.client.NexmoClientException;
import com.nexmo.client.sms.MessageStatus;
import com.nexmo.client.sms.SmsSubmissionResponse;
import com.nexmo.client.sms.messages.TextMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Nexmo 短信
 * @author Administrator
 *
 * 参考地址 ：https://www.nexmo.com
 */
@Slf4j
@Component
@SuppressWarnings("unchecked")
@DependsOn("smsConstants")
public class NexmoSms {

    private static String NEXMO_URL = SmsConstants.NEXMO_URL;
    private static String SENDER_NAME = SmsConstants.SENDER_NAME;
    private static String NEXMO_API_KEY = SmsConstants.NEXMO_API_KEY;
    private static String NEXMO_API_SECRET = SmsConstants.NEXMO_API_SECRET;

    static {
        if(StringUtil.isEmpty(NEXMO_URL)) {
            NexmoSms.NEXMO_URL = "https://rest.nexmo.com/sms/json";
        }
        if(StringUtil.isEmpty(SENDER_NAME)) {
            NexmoSms.SENDER_NAME = "WhiteCoat";
        }
        if(StringUtil.isEmpty(NEXMO_API_KEY)) {
            NexmoSms.NEXMO_API_KEY = "9c267750";
        }
        if(StringUtil.isEmpty(NEXMO_API_SECRET)) {
            NexmoSms.NEXMO_API_SECRET = "H5CqODqOrLRzLtA3";
        }

    }

    private NexmoSms(){

    }
    public static void main(String[] args) {
        String phone = "+8618408279830";
        String content = "Hello from Nexmo Java";
        content = "123";
        sendSmsContent(phone,content,"86");
    }

       /**
        * @description 发送 nexmo 短信
        * @param phone 电话号码
        * @param dial 区号
        * @param content 内容
        * @date     2024/1/30
        * @author   cloud fly
        */
    public static boolean sendSmsContent(String phone,String content,String dial) {
        phone = "+" + dial + phone;
        NexmoClient client = new NexmoClient.Builder()
            .apiKey(NEXMO_API_KEY)
            .apiSecret(NEXMO_API_SECRET)
            .build();

        TextMessage message = new TextMessage(
            // 发送者的名称或号码  WhiteCoat
            "WhiteCoat",
            // 接收者的电话号码  8618408279830
            phone,
            // 短信内容
            content
        );
        boolean flag = false;
        try {
            SmsSubmissionResponse response = client.getSmsClient().submitMessage(message);
            if (response.getMessages().get(0).getStatus() == MessageStatus.OK) {
                flag = true;
                System.out.println("短信已成功发送");
            } else {
                System.out.println("短信发送失败: " + response.getMessages().get(0).getErrorText());
            }
        } catch (NexmoClientException | IOException e) {
            System.err.println("短信发送失败: " + e.getMessage());
        }
        return flag;
    }


}
